import {NgForm} from '@angular/forms';
import {Dictionary} from './page-dictionary';
import {ViewChild} from '@angular/core';
import {PageButton} from './page-button.model';
import {FormValidate} from './page-config.model';
import {BComponent} from './bComponent';

export class BDialogComponent{
  name?:string;
  component?:any;
  data?:BDialog;
}

export class BDialog extends BComponent{
  buttons: PageButton;   // 按钮
  dictionaries: Dictionary; // 字典信息
  validates: FormValidate;  // 表单验证的信息

  @ViewChild('dialogForm') currentForm: NgForm;  // 通过ViewChart装饰器获取页面中的表单对象
  dialogForm: NgForm;
  model: any;  // 表单中要编辑的数据对象

  /**
   * 获取编辑的属性
   * @returns {{}}
   */
  get cols(){
    return this.validates.column;
  }
  /**
   * 获取每个属性输入框是否显示必填标记
   * @returns {{}}
   */
  get colsMust(){
    let res = {};
    Object.keys(this.cols).forEach(field => {
      if ( this.cols[field].validates ) {
        res[field] = typeof this.cols[field].validates.required !== 'undefined' ? true : false;
      }
    });
    return res;
  }

  /**
   * 获取每个属性输入框是否显示标红
   * @returns {{}}
   */
  get colsWarning(){
    let res = {};
    Object.keys(this.validates.formError).forEach(field => {
      res[field] = this.validates.formError[field] ? true : false;
    });
    return res;
  }

  formChanged() {
    if (this.currentForm === this.dialogForm) {return; }
    this.dialogForm = this.currentForm;
    if (this.dialogForm) {
      this.dialogForm.valueChanges
        .subscribe(data => {
          this.onValueChanged(data);
        });
    }
  }

  onValueChanged(data?: any, isValidateAll?: boolean) {
    if (!this.dialogForm) {return; }
    const form = this.dialogForm.form;
    if (this.validates && this.validates.formError) {
      Object.keys(this.validates.formError).forEach(field => {
        // 清除当前错误信息
        this.validates.formError[field] = '';
        const control = form.get(field);
        // isValidateAll:是点击保存时验证
        // control.dirty:在输入框中编写时验证
        if (control && ( isValidateAll ||  control.dirty )) {
          const  messages = this.validates.vMessages[field]; // this.validationMessages[field];
          if (control.errors) {
            Object.keys(control.errors).forEach(key => {
              this.validates.formError[field] += `${messages[key]} `;
            });
          }
        }
      });
    }
  }

  getValudateMsg(field) {
    if (this.config) {
      let pro = this.config.property[field];
      return `[${pro.title}] ${pro.validateMsg.required}`;
    }
    return '';
  }
}
